var sy = sy || {};
sy.data = sy.data || {};// 用于存放临时的数据或者对象

sy.ns = function() {
	var o = {}, d;
	for (var i = 0; i < arguments.length; i++) {
		d = arguments[i].split(".");
		o = window[d[0]] = window[d[0]] || {};
		for (var k = 0; k < d.slice(1).length; k++) {
			o = o[d[k + 1]] = o[d[k + 1]] || {};
		}
	}
	return o;
};

sy.serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (this['value'] != undefined && this['value'].length > 0) {// 如果表单项的值非空，才进行序列化操作
			if (o[this['name']]) {
				o[this['name']] = o[this['name']] + "," + this['value'];
			} else {
				o[this['name']] = this['value'];
			}
		}
	});
	return o;
};

sy.formatString = function(str) {
	for (var i = 0; i < arguments.length - 1; i++) {
		str = str.replace("{" + i + "}", arguments[i + 1]);
	}
	return str;
};

sy.stringToList = function(value) {
	if (value != undefined && value != '') {
		var values = [];
		var t = value.split(',');
		for (var i = 0; i < t.length; i++) {
			values.push('' + t[i]);/* 避免他将ID当成数字 */
		}
		return values;
	} else {
		return [];
	}
};

sy.jsonToString = function(o) {
	var r = [];
	if (typeof o == "string")
		return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
	if (typeof o == "object") {
		if (!o.sort) {
			for ( var i in o)
				r.push(i + ":" + sy.jsonToString(o[i]));
			if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
				r.push("toString:" + o.toString.toString());
			}
			r = "{" + r.join() + "}";
		} else {
			for (var i = 0; i < o.length; i++)
				r.push(sy.jsonToString(o[i]));
			r = "[" + r.join() + "]";
		}
		return r;
	}
	return o.toString();
};
sy.stringToJSON = function(obj){   
    return eval('(' + obj + ')');   
}
sy.trim = function(str) {
	return str.replace(/(^\s*)|(\s*$)/g, '');
};
sy.ltrim = function(str) {
	return str.replace(/(^\s*)/g, '');
};
sy.rtrim = function(str) {
	return str.replace(/(\s*$)/g, '');
};
sy.startWith = function(source, str) {
	var reg = new RegExp("^" + str);
	return reg.test(source);
};
sy.endWith = function(source, str) {
	var reg = new RegExp(str + "$");
	return reg.test(source);
};

//获取url中的参数
sy.getUrlParam = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}
sy.getCookie = function(name) {
    var aCookie = document.cookie.split("; ");
    var lastMatch = null;
    for (var i = 0; i < aCookie.length; i++) {
        var aCrumb = aCookie[i].split("=");
        if (name == aCrumb[0]) {
            lastMatch = aCrumb;
        }
    }
    if (lastMatch) {
        var v = lastMatch[1];
        if (v === undefined) return v;
        return unescape(v);
    }
    return null;
}
sy.setCookie = function(name,value,days,path){   
    var name = escape(name);   
    var value = escape(value);   
    var expires = new Date();   
    expires.setTime(expires.getTime() + days*24*3600000);   
    path = path == "" ? "" : ";path=" + path;   
    _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toGMTString();   
    document.cookie = name + "=" + value + _expires + path;   
}   
sy.delCookie = function(name,path){//为了删除指定名称的cookie，可以将其过期时间设定为一个过去的时间
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var value = sy.getCookie(name);
	path = path == "" ? "" : ";path=" + path;   
	if (value != null) document.cookie = name + "=" + value + ";expires=" + exp.toGMTString() + path;
}

/**IE下解决new Date(str)
 * */	
sy.newDateAndTime = function(dateStr){
	if (!dateStr) return new Date();
	var ds = dateStr.split(" ")[0].split("-");
	var ts = dateStr.split(" ")[1].split(":");
	var r = new Date();
	r.setFullYear(ds[0],ds[1] - 1, ds[2]);
	r.setHours(ts[0], ts[1], ts[2], 0);
	return r;
};

sy.loadNum = 0;
sy.openLoad = function(){
	if(sy.loadNum == 0){
		$(".loading").show();
	}
	sy.loadNum++;
}
sy.closeLoad = function(flag){
	if(flag == 1){
		sy.loadNum = 0;
		$(".loading").hide();
	}else if(sy.loadNum > 0){
		if(sy.loadNum == 1){
			$(".loading").hide();
		}
		sy.loadNum--;
	}
}

sy.alert = function(msg){
//	layer.open({
//	    content: msg,
//	    time: 2
//	});
	//alert(msg);
	sy.msg(msg);
}

sy.msg = function(msg){
	layer.open({
	    content: msg,
	    time: 2
	});
}

sy.confirm = function(msg,yes,no){
//	layer.open({
//	    content: msg,
//	    btn: ['确认', '取消'],
//	    shadeClose: false,
//	    yes: function(){
//	        if(yes)yes();
//	    }, no: function(){
//	    	if(no)no();
//	    }
//	});
	if(confirm(msg)){
		yes();
	}else{
		if(no)no();
	}
}


//日期格式化
Date.prototype.Format = function(fmt){
  var o = {   
    "M+" : this.getMonth()+1,                 //月份   
    "d+" : this.getDate(),                    //日   
    "h+" : this.getHours(),                   //小时   
    "m+" : this.getMinutes(),                 //分   
    "s+" : this.getSeconds(),                 //秒   
    "q+" : Math.floor((this.getMonth()+3)/3), //季度   
    "S"  : this.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
};

$.ajaxSetup({type : 'POST'});
$(document).ajaxStart(function(){
	sy.openLoad();
});
$(document).ajaxStop(function(){
	sy.closeLoad();
});
$(document).ajaxError(function(event,xhr,settings){
	sy.closeLoad();
    if(xhr.responseText=="sessionOut"){
    	$('#loginM').modal("show");
    	//location.href=sy.path+'/m/login';
    }else {
    	try {
			if(XMLHttpRequest.responseText != undefined){
				alert(XMLHttpRequest.responseText);
			}else{
				 
			}
		} catch (e) {
			alert(XMLHttpRequest.responseText);
		}
    }
});

sy.getGeoLocation = function(callBack){
	sy.showLoad();
	if(sessionStorage.lat!=undefined && sessionStorage.lng!=undefined){
		if(callBack){
			sy.closeLoad();
			callBack();
		}
	}else{
		var map, geolocation;
	    //加载地图，调用浏览器定位服务
	    map = new AMap.Map('');
	    map.plugin('AMap.Geolocation', function() {
			geolocation = new AMap.Geolocation({
	            enableHighAccuracy: true,//是否使用高精度定位，默认:true
	            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
	            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
	            convert: true           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
	        });
			map.addControl(geolocation);
			AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
			AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
			geolocation.getCurrentPosition();
			//解析定位结果
		    function onComplete(data) {
		    	sessionStorage.lat = data.position.getLat();
				sessionStorage.lng = data.position.getLng();
				if(callBack){
					sy.closeLoad();
					callBack();
				}
		    }
		    //解析定位错误信息
		    function onError(data) {
		    	sy.closeLoad(1);
		        var str = '定位失败!';
		        str += '[错误信息：'
		        switch (data.info) {
		            case 'PERMISSION_DENIED':
		                str += '浏览器阻止了定位操作';
		                break;
		            case 'POSITION_UNAVAILBLE':
		                str += '无法获得当前位置';
		                break;
		            case 'TIMEOUT':
		                str += '定位超时';
		                break;
		            default:
		                str += '未知错误';
		                break;
		        }
		        alert(str+"]");
		    }
	    });
	}
}
sy.isWeixin = function(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}
sy.isIphone = function(){
    var sUserAgent = navigator.userAgent.toLowerCase();
	return sUserAgent.match(/iphone/i) == "iphone";
}

sy.isAndroid = function(){
	var sUserAgent = navigator.userAgent.toLowerCase();
	return sUserAgent.match(/android/i) == "android" || sUserAgent.match(/Linux/i) == "Linux";
}
sy.isPc = function() {
	//平台、设备和操作系统  
    var system ={  
        win : false,  
        mac : false,  
        xll : false  
    };  
    //检测平台  
    var p = navigator.platform;  
    system.win = p.indexOf("Win") == 0;  
    system.mac = p.indexOf("Mac") == 0;  
    if(system.win||system.mac||system.xll){
        return true;
    }
    return false;
}
function isWeixin(){return sy.isWeixin();}
function isIphone(){return sy.isIphone();}
function isAndroid(){return sy.isAndroid();}
function isPc() {return sy.isPc();}

sy.idcardValid = function(code) { 
 	// 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
	var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	return reg.test(code);
}